﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using HsTec.Mobile.Green.SqlServerDAL;
using Baimasoft.FrameWork.Base;
using Baimasoft.Manage.SqlServerDAL;

public partial class DocumentManage_Document_Add_List : Baimasoft.Web.UI.PageManagerTop
{
    DataFolder MyDF = new DataFolder();
    DataFile datafile = new DataFile();
    Machineroom machineroom = new Machineroom();
    Network MyNt = new Network();
    Area area = new Area();
    Project project = new Project();
    LogManage MyLog = new LogManage();


    BaimasoftFile MyFile = new BaimasoftFile();

    public string sID = "-1";

    protected void Page_Load(object sender, EventArgs e)
    {
        this.BindControlEvent();
        this.HiddenID.Value = "";

        if (this.Request.Params["ID"] != null)
        {
            sID = this.Request.Params["ID"].Trim();
        }
        else
        {
            sID = "-1";
        }
        if (!this.IsPostBack)
        {
            ChoiceDt.Checked = true;
            ifChoiceDt.Style.Add("display", "");
            AllDt.Style.Add("display", "none");
            GridView1.Attributes.Add("BorderColor", "LightSkyBlue");
            this.SDT.Text = DateTime.Now.ToString("yyyy-MM") + "-01";
            this.EDT.Text = DateTime.Now.ToString("yyyy-MM-dd");
            ddlRegionDataBind();
            ddlMachineDataBind();
            ddlnetworkDataBind();
            ddlProjectDataBind();
            this.BindGridViewData();//绑定GridView,为删除服务
        }
    }


    /// <summary>
    /// 数据绑定
    /// </summary>
    protected override void BindGridViewData()
    {
        //this.DataSource = datafile .GetDataFileInfos (GetSearchString());
        this.DataSource = datafile.GetDataFileInfos("");
        this.DataSource.DefaultView.Sort = this.SortString;
        GridView1.DataSource = this.DataSource.DefaultView;
        GridView1.DataBind();
        KeepStyle();
    }


    /// <summary>
    /// 区域下拉框
    /// </summary>
    protected void ddlRegionDataBind()
    {
        ddlRegionid.DataSource = area .GetAreaInfos (string.Empty);
        ddlRegionid.DataBind();
        ddlRegionid.Items.Insert(0, "全部");
        ddlRegionid.Items[0].Value = "0";
    }

    /// <summary>
    /// 机房下拉框绑定
    /// </summary>
    protected void ddlMachineDataBind()
    {
        ddlMachineid.DataSource = machineroom .GetMachineRooms ("");
        ddlMachineid.DataBind();
        ddlMachineid.Items.Insert(0, "全部");
        ddlMachineid.Items[0].Value = "0";
    }

    /// <summary>
    /// 网元下拉框绑定
    /// </summary>
    protected void ddlnetworkDataBind()
    {
        ddlnetwork.DataSource = MyNt .GetNetWorks ("");
        ddlnetwork.DataBind();
        ddlnetwork.Items.Insert(0, "全部");
        ddlnetwork.Items[0].Value = "0";
    }

    /// <summary>
    /// 项目下拉框
    /// </summary>
    protected void ddlProjectDataBind()
    {
        this.ddlProject.DataSource = project .GetProjectInfos ("");
        this.ddlProject.DataBind();
        this.ddlProject.Items.Insert(0, "全部");
        this.ddlProject.Items[0].Value = "0";
    }  

    /// <summary>
    /// 删除按钮
    /// </summary>
    /// <param name="ids"></param>
    protected override void Delete(string ids)
    {
        int iFileStatus = 0;
        DataFile datafile1 = new DataFile();
        string sid = ids;
        string[] ASid = sid.Split(',');
        int iSid = ASid.Length;
        for (int i = 0; i <= iSid - 1; i++)
        {
            string sName = "";
            string m_Root = "";
            string str = "", str2 = "";
            //判断该文档是否已归档
            int iback = datafile .GetCountByqueryStr(" ID='" + ASid[i] + "'  and Status='1' ");
            if (iback <= 0)
            {
                DataTable MyDT = datafile.GetDataFileInfo(Convert.ToInt32(ASid[i]));
                foreach (DataRow dr in MyDT.Rows)
                {
                    sName = dr["AliasName"].ToString().Trim();
                    m_Root = ConfigurationManager.AppSettings["DocumentMange"];  //取Web.Config文件中的配置信息
                    str = m_Root + HPath.Value.ToString().Trim() + "\\" + sName;              //写到服务器上的路径
                    str2 = m_Root + HPath.Value.ToString().Trim() + "\\" + dr["Name"].ToString().Trim();

                    try
                    {
                        MyFile.DeleteFile(str);  //删除服务器上得文件
                        datafile .DeleteDataFileInfo("id="+ (ASid[i]));  //删除数据库中的记录 
                    }
                    catch
                    {
                    }
                    //日志
                    try
                    {
                        string sPerID = (string)Session["Baimasoft_Pers_ID"];
                        string sContent = "用户" + (string)Session["Baimasoft_User_LogonID"] + "删除文件：" + str2;
                        string sIP = Page.Request.UserHostAddress;
                        MyLog.InsertLog("3", sPerID, sContent, sIP);
                    }
                    catch
                    {
                    }
                }
            }
            iFileStatus += iback;
        }
        if (iFileStatus > 0)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('已归档的文档,不允许删除!');</script>");
            return;
        }
    }


    /// <summary>
    /// 获取查询条件
    /// </summary>
    /// <returns></returns>
    protected override string GetSearchString()
    {
        string searchStr = string.Empty;


        searchStr += " ( FolderID = '" + sID + "')   ";

        if (this.Name.Text.Trim().Length > 0)
        {
            searchStr += " and a.Name like '%" + this.Name.Text.ToString().Trim() + "%' ";
        }
        if (this.KeyWord.Text.Trim().Length > 0)
        {
            searchStr += " and a.KeyWord like '%" + this.KeyWord.ToString().Trim() + "%' ";
        }

        if (ChoiceDt.Checked == true)
        {
            if (this.SDT.Text.ToString().Trim() != "")
            {
                searchStr += " and convert(varchar(10),a.CreatDT,120) >= '" + this.SDT.Text.ToString().Trim() + "' ";
            }
            else
            {
                searchStr += " and convert(varchar(10),a.CreatDT,120) >= '" + DateTime.Now.ToString("yyyy-MM-dd") + "' ";
            }
            if (this.EDT.Text.ToString().Trim() != "")
            {
                searchStr += " and convert(varchar(10),a.CreatDT,120) <= '" + this.EDT.Text.ToString().Trim() + "' ";
            }
            else
            {
                searchStr += " and convert(varchar(10),a.CreatDT,120) <= '" + DateTime.Now.ToString("yyyy-MM-dd") + "' ";
            }
        }

        string sddlRegionid = ddlRegionid.SelectedValue .ToString ().Trim ();
        if (sddlRegionid != "0")
        {
            searchStr += " and a.Region ='" + sddlRegionid + "' ";
        }
        if (ddlMachineid.SelectedValue.ToString().Trim() != "0")
        {
            searchStr += " and a.MachineRoom ='" + ddlMachineid.SelectedValue.ToString().Trim() + "' ";
        }
        if (ddlnetwork.SelectedValue.ToString().Trim() != "0")
        {
            searchStr += " and a.NetWork ='" + ddlnetwork.SelectedValue.ToString().Trim() + "' ";
        }
        if (ddlProject.SelectedValue.ToString().Trim() != "0")
        {
            searchStr += " and a.Project ='" + ddlProject.SelectedValue.ToString().Trim() + "' ";
        }

        //取该用户数据角色授权信息
        string sChoiceFolderCol = AspNetHelper.GetRightFolderIDCol();
        string sChoiceFileCol = AspNetHelper.GetRightFileIDCol();

        if ((sChoiceFolderCol.Trim() == "0" || sChoiceFolderCol.Length == 0) && (sChoiceFileCol.Trim() == "0" || sChoiceFileCol.Length == 0))
        { //没有授权的情况下
            //searchStr += " and  ( 1<>1 )";
        }
        else
        {

            if (sChoiceFolderCol.Trim() != "0" && sChoiceFolderCol.Length > 0)
            {
                string sFolderIDCols = MyDF.GetFolderChildIDCols(sChoiceFolderCol.Trim());
                if (sFolderIDCols != "")
                {
                    searchStr += " and a.FolderID in(" + sFolderIDCols + ") ";
                    //searchStr += " and a.FolderID in(SELECT ChildIDCols FROM DataFolder WHERE (ID in(" + sFolderIDCols + "))) ";
                }
            }

            if (sChoiceFileCol.Trim() != "0" && sChoiceFileCol.Length > 0)
            {

                //自己的文档自己可以查看
                string sLogonID = "";
                try
                {
                    sLogonID = Session["Baimasoft_User_LogonID"].ToString();
                }
                catch
                {
                }
                if (sLogonID == "")
                {
                    sLogonID = "0";
                }


                if (sLogonID.ToUpper() != "ADMIN")
                {
                    searchStr += "  and (a.ID in(" + sChoiceFileCol + ") or a.creatrole = '" + sLogonID + "' )  ";
                }
                else
                {
                    searchStr += " and a.ID in(" + sChoiceFileCol + ") ";
                }
                //
            }
        }

        searchStr += " order by a.name, versionnumber desc ";

        return searchStr; 
    }


    /// <summary>
    /// 更新信息
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void BtnRefresh1_Click(object sender, EventArgs e)
    {
        this.DataSource = datafile.GetDataFileInfos(GetSearchString());
        this.DataSource.DefaultView.Sort = this.SortString;
        GridView1.DataSource = this.DataSource.DefaultView;
        GridView1.DataBind();
        KeepStyle();
    }

    /// <summary>
    /// 更新
    /// </summary>
    protected void BtnRefresh()
    {
        this.DataSource = datafile.GetDataFileInfos(GetSearchString());
        this.DataSource.DefaultView.Sort = this.SortString;
        GridView1.DataSource = this.DataSource.DefaultView;
        GridView1.DataBind();
        KeepStyle();
    }

    /// <summary>
    /// 文档移动
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void BtnMove_Click(object sender, EventArgs e)
    {
        DataFile datafile1 = new DataFile();
        string m_Root =  ConfigurationManager.AppSettings["DocumentMange"];    //取Web.Config文件中的配置信息

        string sid = "";
        foreach (GridViewRow row in GridView1.Rows)
        {
            System.Web.UI.HtmlControls.HtmlInputCheckBox check = (System.Web.UI.HtmlControls.HtmlInputCheckBox)row.FindControl("check");
            if (check.Checked)
            {
                sid += check.Value + ",";
            }
        }

        if (sid.Length > 0)
        {
            sid = sid.TrimEnd((new char[] { ',' }));
        }

        int icount = 0;
        string[] ASid = sid.Split(',');
        int iSid = ASid.Length;
        string sLeave = "";
        string strChoice = "", strChoice2 = ""; //现文件所在路径
        string sHChoiceID = HChoiceID.Value.ToString().Trim();
        string sChoicePath = MyDF.GetFileMovePath(sHChoiceID);
        if (ASid[0].Length != 0)
        {
            for (int i = 0; i <= iSid - 1; i++)
            {
                string sName = "";
                string str = "", str2 = "";    //原文件所在路径
                if (ASid[i].Length > 0)
                {
                    DataTable MyDT2 = datafile.GetDataFileInfo(Convert.ToInt32(ASid[i]));  //取各文件的相关信息；
                    foreach (DataRow dr in MyDT2.Rows)
                    {
                        sName = dr["AliasName"].ToString().Trim();
                        str = m_Root + HPath.Value.ToString().Trim() + "\\" + sName;  //原路径
                        str2 = m_Root + HPath.Value.ToString().Trim() + "\\" + dr["Name"].ToString().Trim();  //原路径

                        strChoice = m_Root + sChoicePath + "\\" + sName;              //现路径
                        strChoice2 = m_Root + sChoicePath + "\\" + dr["Name"].ToString().Trim();              //现路径

                        int iback = datafile.FileMove(sHChoiceID, ASid[i].ToString());  //更改数据库
                        if (iback > 0)
                        {
                            icount = icount + iback;  //移动文档记录器
                            MyFile.MoveFile(str, strChoice); //移动物理文档

                            //日志
                            try
                            {
                                string sPerID = (string)Session["Baimasoft_Pers_ID"];
                                string sContent = "用户" + (string)Session["Baimasoft_User_LogonID"] + "文件从：" + str2 + "移动到：" + strChoice2;
                                string sIP = Page.Request.UserHostAddress;
                                MyLog.InsertLog("3", sPerID, sContent, sIP);
                            }
                            catch
                            {
                                string sPerID = "0";
                                string sContent = "文件从：" + str + "移动到：" + strChoice;
                                string sIP = Page.Request.UserHostAddress;
                                MyLog.InsertLog("3", sPerID, sContent, sIP);
                            }

                        }
                    }
                }
            }


            if (icount > 0)
            {
                if (iSid == icount)
                {
                    sLeave = "文档移动成功！";
                }
                else
                {
                    sLeave = "部分文档移动成功！";
                }
            }
            else
            {
                sLeave = "文档移动失败！";
            }
        }
        else
        {
            sLeave = "请选择文档后,再点击“移动文档”按钮！";
        }

        BtnRefresh();
        ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + sLeave + "');</script>"); 
    }



    protected void ddlRegionid_SelectedIndexChanged(object sender, EventArgs e)
    {
        string sddlRegion = ddlRegionid.SelectedValue.ToString().Trim();

        DataTable dt1 = machineroom.GetMachineRooms ("a.region_id='" + sddlRegion + "'");
        this.ddlMachineid.DataValueField = "mroom_id";
        this.ddlMachineid.DataTextField = "mroom_name";
        this.ddlMachineid.DataSource = dt1;
        this.ddlMachineid.DataBind();

        string sddlMachine = ddlMachineid.SelectedValue.ToString().Trim();
        DataTable dt2 = MyNt.GetNetWorks("a.mroom_id = '" + sddlMachine + "'");
        this.ddlnetwork.DataValueField = "netw_id";
        this.ddlnetwork.DataTextField = "netw_name";
        this.ddlnetwork.DataSource = dt2;
        this.ddlnetwork.DataBind();
        KeepStyle();

    }
    protected void ddlMachineid_SelectedIndexChanged(object sender, EventArgs e)
    {
        string sddlMachine = ddlMachineid.SelectedValue.ToString().Trim();
        DataTable dt2 = MyNt.GetNetWorks ("a.mroom_id = '" + sddlMachine + "'");
        this.ddlnetwork.DataValueField = "netw_id";
        this.ddlnetwork.DataTextField = "netw_name";
        this.ddlnetwork.DataSource = dt2;
        this.ddlnetwork.DataBind();
        KeepStyle();
    }

    /// <summary>
    /// 保存相应的状态
    /// </summary>
    protected void KeepStyle()
    {
        if (ChoiceDt .Checked == true)
        {
            ifChoiceDt.Style.Add("display", "");
            AllDt.Style.Add("display", "none");
            LDt.Value = "";
        }
        else
        {
            ifChoiceDt.Style.Add("display", "none");
            AllDt.Style.Add("display", "");
            LDt.Value = "全部日期";
        }
    }

    /// <summary>
    /// 软件删除  0 正常, 1 归档  2 软删除
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void DeleteDoc_Click(object sender, EventArgs e)
    {
        string sID = "", sFileNameCol = "";
        
        System.Web.UI.HtmlControls.HtmlInputCheckBox check;

        foreach (GridViewRow row in GridView1.Rows)
        {
            check = (System.Web.UI.HtmlControls.HtmlInputCheckBox)row.FindControl("check");
            if (check.Checked)
            {
                sID += check.Value + ",";

                GridViewRow selectedRow = GridView1.Rows[row.RowIndex] ;

                TableCell contactFE = selectedRow.Cells[1];  //Name
                sFileNameCol += contactFE.Text.ToString().Trim();
            }
        }

        sID = sID.TrimEnd(',').ToString().Trim();

        HsTec.Mobile.Green.SqlServerDAL.DataFile MyDF = new DataFile();
        int iback = MyDF.DeleteDataFile(" id in(" + sID + ")");
        if (iback > 0)
        {
            //日志
            try
            {
                string sPerID = (string)Session["Baimasoft_Pers_ID"];
                string sContent = "用户" + (string)Session["Baimasoft_User_LogonID"] + "软删除文件" + sFileNameCol;
                string sIP = Page.Request.UserHostAddress;
                MyLog.InsertLog("3", sPerID, sContent, sIP);
            }
            catch
            {
            }

            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('软删除成功!');</script>");
            return;
        }
        else
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('软删除失败!');</script>");
            return;
        }
    }
}